package net.neiquan.neiquandemowithkf.fragment;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.pizidea.imagepicker.AndroidImagePicker;
import com.pizidea.imagepicker.ImageUtils;
import com.pizidea.imagepicker.bean.ImageItem;
import com.pizidea.imagepicker.image.ImagesGridActivity;

import net.neiquan.neiquandemowithkf.R;
import net.neiquan.neiquandemowithkf.api.NetUtils;
import net.neiquan.neiquandemowithkf.application.MyApplication;
import net.neiquan.neiquandemowithkf.entity.User;
import net.neiquan.neiquandemowithkf.utils.Tools;
import net.neiquan.neiquandemowithkf.utils.UploadImage2OSS;
import net.neiquanlib.base.AppBaseFragment;
import net.neiquanlib.dialog.AlertChooser;
import net.neiquanlib.http.NetCallBack;
import net.neiquanlib.http.ResultModel;
import net.neiquanlib.inter.UserEvent;
import net.neiquanlib.numberpicker.view.AlertPickerSingle;
import net.neiquanlib.utils.LogC;
import net.neiquanlib.widget.RoundImageView;

import org.greenrobot.eventbus.EventBus;
import org.haitao.common.utils.CameraUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * 作者 ： hjb
 * 时间 ： 2016/7/22.
 */

public class ModifyInfoFragment extends AppBaseFragment {
    @InjectView(R.id.head_img)
    RoundImageView mHeadImg;
    @InjectView(R.id.nickName_et)
    EditText mNickNameEt;
    @InjectView(R.id.sex_Tv)
    TextView mSexTv;
    private String imagePath;
    private int sex;

    @Override
    public View initRootView() {
        rootView = mInflater.inflate(R.layout.fragment_modify_info, null);
        ButterKnife.inject(this, rootView);
        return rootView;
    }

    @Override
    public void setViews() {
        setNextTv("保存");
        setTitleTv("个人资料");
        setNextOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(imagePath)) {
                    Toast.makeText(getActivity(), "请上传头像", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(mNickNameEt.getText().toString().trim())) {
                    Toast.makeText(getActivity(), "请填写昵称", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(mSexTv.getText().toString().trim())) {
                    Toast.makeText(getActivity(), "请选择性别", Toast.LENGTH_SHORT).show();
                } else {
                    Tools.showDialog(mContext);
                    UploadImage2OSS.uploadImage(getActivity(), imagePath, new UploadImage2OSS.OnUploadImageListener() {
                        @Override
                        public void onSuccess(String successImg) {
                            LogC.e("----上传成功-----" + successImg);
                            sendToService(successImg);
                        }

                        @Override
                        public void onFail(String errorMessage) {
                            Tools.dismissWaitDialog();
                            Toast.makeText(mContext, "上传失败", Toast.LENGTH_SHORT).show();
                            LogC.e("----上传失败----" + errorMessage);
                        }
                    });
                }
            }
        });
    }

    private void sendToService(String photo) {
        NetUtils.getInstance().userInfo(photo, mNickNameEt.getText().toString().trim(), sex, new NetCallBack() {
            @Override
            public void onSuccess(String message, int errorCode, String response, ResultModel model) {
                Tools.dismissWaitDialog();
                User user = model.getModel();
                User mUser = MyApplication.getInstance().mUser;
                if (mUser != null) {
                    user.setUserToken(mUser.getUserToken());
                }
                MyApplication.getInstance().saveUser(user);
                EventBus.getDefault().post(new UserEvent(UserEvent.UPDATE_INFO));
                finish();
                LogC.e("----上传成功-----sendToService");
            }

            @Override
            public void onFail(String message, int errorCode, boolean dataError) {
                Tools.dismissWaitDialog();
                Toast.makeText(getActivity(), "上传失败", Toast.LENGTH_SHORT).show();
                LogC.e("----上传失败-----sendToService");
            }
        }, User.class);
    }

    @Override
    public void initData() {
        //设置缓存
        User mUser = MyApplication.getInstance().mUser;
        if (mUser != null) {
            if (mUser.getHeadUrl() != null) {
                ImageUtils.LoadPicture(mUser.getHeadUrl(), mHeadImg);
            }
            mNickNameEt.setText(mUser.getNickName() != null ? mUser.getNickName() : "");
            mNickNameEt.setSelection(mNickNameEt.getText().length());
            int sex = mUser.getSex();
            mSexTv.setText(sex == 0 ? "男" : "女");
        }
    }

    private void showAlertChooser() {
        new AlertChooser.Builder(getActivity()).setTitle("选择图片").addItem("相机", new AlertChooser.OnItemClickListener() {
            @Override
            public void OnItemClick(AlertChooser chooser) {
                chooser.dismiss();
                CameraUtils.takePhoto(getActivity());
            }
        }).addItem("相册", new AlertChooser.OnItemClickListener() {
            @Override
            public void OnItemClick(AlertChooser chooser) {
                AndroidImagePicker.getInstance().setSelectMode(AndroidImagePicker.Select_Mode.MODE_SINGLE);
                //AndroidImagePicker.Select_Mode.MODE_SINGLE单选模式
                //AndroidImagePicker.Select_Mode.MODE_MULTI多选模式
                //AndroidImagePicker.getInstance().setSelectLimit(MAX_NUM);//多选模式下  最多选多少张
                AndroidImagePicker.getInstance().setShouldShowCamera(false);//相册里面是否显示拍照按钮
                Intent intent = new Intent(getActivity(), ImagesGridActivity.class);
                startActivityForResult(intent, CameraUtils.LOCAL_PICTURE);
                chooser.dismiss();
            }
        }).setNegativeItem("取消", new AlertChooser.OnItemClickListener() {
            @Override
            public void OnItemClick(AlertChooser chooser) {
                chooser.dismiss();
            }
        }).show();
    }

    @OnClick({R.id.head_Rl, R.id.sex_Rl})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.head_Rl:
                showAlertChooser();
                break;
            case R.id.sex_Rl:
                ArrayList<String> strings = new ArrayList<>();
                strings.add("男");
                strings.add("女");
                new AlertPickerSingle.Builder(getActivity())
                        .setData(strings)
                        .setTitle("性别")
                        .setOnItemSelectListener(new AlertPickerSingle.OnItemSelectListener() {
                            @Override
                            public void endSelect(AlertPickerSingle chooser, boolean isCancel, int id, String text) {
                                if (text.equals("男")) {
                                    sex = 0;
                                } else {
                                    sex = 1;
                                }
                                mSexTv.setText(text);
                            }
                        }).show();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CameraUtils.LOCAL_PICTURE) {
            List<ImageItem> imageList = AndroidImagePicker.getInstance().getSelectedImages();
            if (imageList != null && imageList.size() > 0) {
                imagePath = imageList.get(0).getPath();
                ImageUtils.LoadPicture(ImageUtils.IMAGE_FILE + imagePath, mHeadImg);
            }
        } else if (requestCode == CameraUtils.TAKE_PICTURE) {
            imagePath = CameraUtils.photoPath;
            ImageUtils.LoadPicture(ImageUtils.IMAGE_FILE + imagePath, mHeadImg);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
